package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.GulimallElaticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.fegin.ProductFeginService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.AttrRespVO;
import com.atguigu.gulimall.search.vo.BrandVO;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.ml.job.results.Bucket;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName MallSearchServiceImpl
 * @Description TODO
 * @Author 13290
 * @Date 2022/10/9 15:00
 **/
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    ProductFeginService productFeginService;

    @Autowired
    private RestHighLevelClient client;

    @Override
    public SearchResult search(SearchParam param) {
        //1.动态构建出DSL语句
        SearchResult result = null;

        //准备检索请求
        //SearchRequest searchRequest = new SearchRequest();

        //构建检索请求
        SearchRequest searchRequest = buildSearchRequest(param);

        try {
            //2.执行检索请求
            SearchResponse response = client.search(searchRequest, GulimallElaticSearchConfig.COMMON_OPTIONS);

            //3.分析响应数据,封装成我们需要的格式
            result = buildSearchResult(response,param);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 准备检索请求
     * #模糊匹配,过滤(属性,价格,品牌,库存,分类)匹配,排序,分页,高亮,聚合分析
     * #如果是嵌入式的属性,查询,聚合,分析 都应该用嵌入式的
     * @Date 9:11 2022/10/13
     * @param
     * @Return org.elasticsearch.action.search.SearchRequest
     **/
    private SearchRequest buildSearchRequest(SearchParam param) {
        //DSL语句构建者
        SearchSourceBuilder builder = new SearchSourceBuilder();

        /*
         * 构建
         * 查询:模糊匹配,过滤(属性,价格,品牌,库存,分类)匹配
         **/
        //1.构建bool - query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1 must 模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }

        //1.2 bool - filter 过滤 三级分类id
        if (param.getCatalog3Id() != null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
        //1.2 bool - filter 过滤 品牌id
        if (param.getBrandId() != null && param.getBrandId().size()>0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }
        //1.2 bool - filter 过滤 所有指定的属性
        if (param.getAttrs() != null && param.getAttrs().size() > 0){
            for (String attrStr:param.getAttrs()
                 ) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                //属性id
                String attrId = s[0];
                //属性值
                String[] attrValues = s[1].split("_");

                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                //每一个内嵌查询  都需要生成一个nestedQuery
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }

        //1.2 bool - filter 过滤 是否存在库存
        if (param.getHasStock() != null){
            boolQuery.filter(QueryBuilders.termQuery("hasStock",param.getHasStock() ==1));
        }

        //1.2 bool - filter 按照价格区间
        if (!StringUtils.isEmpty(param.getSkuPrice())){
            //1_500/_500/500/
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("sukPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2){
                //区间
                rangeQuery.gte(s[0]).lte(s[1]);
            }else if (s.length == 1){
                if (param.getSkuPrice().startsWith("_")){
                    rangeQuery.lte(s[0]);
                }
                if (param.getSkuPrice().endsWith("_")){
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }

        //把查询条件  都进行封装之后 进行查询
        builder.query(boolQuery);
        /*
         * 构建
         * 排序,分页,高亮
         **/
        if(!StringUtils.isEmpty(param.getSort())){
            String sort = param.getSort();
            String[] s = sort.split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc")? SortOrder.ASC:SortOrder.DESC;
            builder.sort(s[0],order);
        }
        //分页 pageSize:5
        // pageNum:1 from :0 size:5
        //pageNum:2 from:5 size:5
        //from = (pageNum - 1) * size
        builder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        builder.size(EsConstant.PRODUCT_PAGESIZE);

        //高亮
        if (!StringUtils.isEmpty(param.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style = 'color:red'>");
            highlightBuilder.postTags("</b>");
            builder.highlighter(highlightBuilder);
        }
        /*
         * 构建
         * 聚合分析
         **/
        //TODO 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);

        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(50));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(50));

        builder.aggregation(brand_agg);

        //TODO 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(50);

        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catelogName").size(1));

        builder.aggregation(catalog_agg);

        //TODO 属性聚合 嵌入聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        //attr_agg 的子聚合 attr_id_agg
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(10);

        //attr_id_agg 的子聚合 attr_name_agg,attr_value_agg
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(10));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(10));

        attr_agg.subAggregation(attr_id_agg);

        builder.aggregation(attr_agg);


        String s = builder.toString();
        System.out.println("构建的DSL语句" + s);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, builder);

        return searchRequest;
    }

    /**
     * 构建结果数据
     * @Date 9:13 2022/10/13
     * @param response
     * @Return com.atguigu.gulimall.search.vo.SearchResult
     **/
    private SearchResult buildSearchResult(SearchResponse response,SearchParam param) {

        SearchResult result = new SearchResult();
        //1.返回的所有查询到的商品
        //获取命中记录
        SearchHits hits = response.getHits();

        ArrayList<SkuEsModel> esModels = new ArrayList<>();

        if (hits.getHits() != null && hits.getHits().length > 0){
            for (SearchHit hit:
                    hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    esModel.setSkuTitle(string);
                }

                esModels.add(esModel);
            }
        }
        result.setProducts(esModels);

        //2.当前所有商品涉及到的所有属性信息
        ArrayList<SearchResult.AttrVO> attrVOS = new ArrayList<>();
        //获取所有聚合信息
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVO attrVO = new SearchResult.AttrVO();
            //1.得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVO.setAttrId(attrId);
            //2.得到属性的名字
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVO.setAttrName(attrName);
            //3.得到属性的值
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = attr_value_agg.getBuckets().stream().map(item -> {
                String keyAsString = item.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVO.setAttrValue(attrValues);

            attrVOS.add(attrVO);

        }
        result.setAttrs(attrVOS);

        //3.当前商品所涉及的品牌信息
        ArrayList<SearchResult.BrandVO> brandVOS = new ArrayList<>();

        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> brandAggBuckets = brand_agg.getBuckets();
        for (Terms.Bucket bucket:brandAggBuckets
             ) {
            SearchResult.BrandVO brandVO = new SearchResult.BrandVO();
            //1.设置品牌的id
            brandVO.setBrandId(bucket.getKeyAsNumber().longValue());
            //2.设置品牌的名字
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVO.setBrandName(brandName);
            //3.设置品牌的图片
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVO.setBrandImg(brandImg) ;
            brandVOS.add(brandVO);
        }


        result.setBrands(brandVOS);
        //4.当前商品所涉及的分类信息

        ArrayList<SearchResult.CatalogVO> catalogVOS = new ArrayList<>();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        //获取bucket
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket: buckets
             ) {
            SearchResult.CatalogVO catalogVO = new SearchResult.CatalogVO();
            //得到分类id
            catalogVO.setCatalogId(Long.parseLong(bucket.getKeyAsString()));

            //得到分类名  获取catalog_agg 的子聚合
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            //获取子聚合中buckets集合  获取第一个数据的key  就是需要的数据
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVO.setCatelogName(catalogName);


            catalogVOS.add(catalogVO);
        }
        result.setCatalogs(catalogVOS);

        //============以上从商品聚合信息获取=============

        //5.当前商品所涉及到的分页信息
        result.setPageNum(param.getPageNum());
        //6.分页信息总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //分页信息-总页码-计算
        int totalPages = (int)total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int)total/EsConstant.PRODUCT_PAGESIZE : (int)(total/EsConstant.PRODUCT_PAGESIZE+1);

        result.setTotalPages(totalPages);

        ArrayList<Integer> pageNavs = new ArrayList<>();

        for (int i = 1; i<= totalPages;i++){
            pageNavs.add(i);
        }

        result.setPageNavs(pageNavs);

        //7.构建面包屑导航功能
        if (param.getAttrs() != null && param.getAttrs().size() > 0){
            List<SearchResult.NavVO> navVOS = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVO navVO = new SearchResult.NavVO();
                String[] s = attr.split("_");

                R r = productFeginService.attrInfo(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode() == 0){
                    AttrRespVO data = r.getData("attr", new TypeReference<AttrRespVO>() {
                    });
                    navVO.setNavName(data.getAttrName());
                }else {
                    navVO.setNavName(s[0]);
                }
                navVO.setNavValue(s[1]);

                String replace = replaceQueryString(param, attr,"attrs");

                navVO.setLink("http://localhost:11111/list.html?"+replace);
                return navVO;
            }).collect(Collectors.toList());

            result.setNavs(navVOS);
        }
        //品牌分类
        if(param.getBrandId() != null && param.getBrandId().size() > 0){
            List<SearchResult.NavVO> navs = result.getNavs();
            SearchResult.NavVO navVO = new SearchResult.NavVO();
            navVO.setNavName("品牌");
            //TODO 远程查询所有品牌
            R r = productFeginService.brandInfo(param.getBrandId());
            if (r.getCode() == 0){
                List<BrandVO> brand = r.getData("data", new TypeReference<List<BrandVO>>() {

                });
                StringBuffer buffer = new StringBuffer();
                String replace = "";
                for (BrandVO brandVo: brand
                     ) {
                    buffer.append(brandVo.getBrandName() + ";");
                    replace = replaceQueryString(param, brandVo.getBrandId() + "", "brandId");
                }
                navVO.setNavValue(buffer.toString());
                navVO.setLink("http://localhost:11111/list.html?"+replace);
            }

            navs.add(navVO);
        }

        //TODO 分类: 不需要导航取消



        return result;
    }

    private String replaceQueryString(SearchParam param, String value,String key) {
        //取消了面包屑 跳转
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("+","%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String replace = param.get_queryString().replace("&"+key+ "=" + encode, "");
        return replace;
    }


}
